﻿Imports Microsoft.TeamFoundation.Client

Public Delegate Sub OnTeamServerSelected(ByVal TeamServer As TeamFoundationServer)

Public Class ServerSelectionControl

    Public Event TeamServerSelected As OnTeamServerSelected

    Private m_TeamServer As TeamFoundationServer

    Public ReadOnly Property TeamServer() As TeamFoundationServer
        Get
            If m_TeamServer Is Nothing Then
                If Not String.IsNullOrEmpty(My.Settings.TeamServer) Then
                    m_TeamServer = TeamFoundationServerFactory.GetServer(My.Settings.TeamServer)
                    If Not m_TeamServer.HasAuthenticated Then
                        Try
                            m_TeamServer.Authenticate()
                            If m_TeamServer.HasAuthenticated Then
                                RaiseEvent TeamServerSelected(m_TeamServer)
                            Else
                                Me.ux_ComboBoxServer.SelectedValue = Nothing
                                MsgBox("Can't authenticate with team server")
                                RaiseEvent TeamServerSelected(Nothing)
                            End If
                        Catch ex As Exception
                            MessageBox.Show(ex.Message, My.Application.Info.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error)
                            RaiseEvent TeamServerSelected(Nothing)
                        End Try
                    Else
                        RaiseEvent TeamServerSelected(m_TeamServer)
                    End If
                End If
            End If
            Return m_TeamServer
        End Get
    End Property

    Private Sub SelectServerControl_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Me.ux_ComboBoxServer.Items.AddRange(Microsoft.TeamFoundation.Client.RegisteredServers.GetServerNames)
        If Not TeamServer Is Nothing Then
            Me.ux_ComboBoxServer.SelectedText = TeamServer.Name
        End If
    End Sub


    Private Sub ux_ComboBoxTeamServers_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ux_ComboBoxServer.SelectedIndexChanged
        My.Settings.TeamServer = CStr(Me.ux_ComboBoxServer.SelectedItem)
        m_TeamServer = Nothing
        Me.ux_ComboBoxServer.SelectedText = TeamServer.Name
    End Sub

End Class
